/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.cas.management.authentication.handler.support;

import org.qloudgen.sec.cas.support.user.services.User;
import org.qloudgen.sec.cas.support.user.services.UsersManager;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.memory.UserMap;
import org.springframework.security.core.userdetails.memory.UserMapEditor;

import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * Check login user is cas management user.  
 * Must be type : org.springframework.security.core.userdetails.UserDetailsService
 *
 * @author mike
 */
public final class CheckManagementUserAuthenticationHandler implements UserDetailsService {
	
	private UserMap userMap = new UserMap();

    /** Instance of logging for subclasses. */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private UsersManager usersManager ;
    
    private final String str = "=123456,ROLE_ADMIN";
    
    public CheckManagementUserAuthenticationHandler(UsersManager usersManager){
    	  this.usersManager = usersManager;
    	  logger.warn("{} init.............",getClass().getName());
    }
    
    public UserDetails loadUserByUsername(String username){
    	  Properties pro = new Properties();
    	  
    	  User user = usersManager.findUserByName(username);
    	  
    	  
    	  if (user == null)
    	      return userMap.getUser(username);
    	  if (usersManager.checkUserIsManagementAdmin(user)){
			    	  String arg = username + str;
			    	  try{
				    	  	InputStream inputStream = new ByteArrayInputStream(arg.getBytes());
				    	    pro.load(inputStream);
			    	  }catch(IOException e){
			    	  }
    	  } else if (!usersManager.checkUserIsManagementAdmin(user))
    	       return userMap.getUser(username);    	  
    	  logger.debug("load Properties CheckManagementUserAuthenticationHandler ....................{}",pro);
    	  
    	  UserMap map = new UserMap();
    	  userMap = UserMapEditor.addUsersFromProperties(map, pro);
    	  
    	  
    	  logger.debug("end CheckManagementUserAuthenticationHandler ....................{}",userMap.getUser(username));
    	  return userMap.getUser(username);
    }
}
